const Koa = require('koa');

const app = new Koa();

const query = require('./db/index.js');

// koa-static   处理静态资源  

const static = require('koa-static');

const path = require('path');

app.use(static(path.join(__dirname,'./public')));

// const bodyparser = require('koa-bodyparser');

const bodyparser = require('./middleware/bodyparser.js');

app.use(bodyparser());

// app.use(async () => {})

const Router = require('koa-router');

const router = new Router();

app.use(router.routes());

app.use(router.allowedMethods());

//获取列表的接口 查询
router.get('/api/list',async (ctx,next) => {
    //1.查看第几页数据 pagenum  2.每页展示条数  limit=2

    /**
     * 1  0  2
     * 2  2  2
    */

    let {pagenum=1,limit=2} = ctx.query;

    let startIndex = (pagenum-1)*limit;

    let list = await query(`select * from list limit ${startIndex},${limit}`);
    //总数
    let total = await query('select count(*) from list');

    console.log(total[0]['count(*)']); //[{ 'count(*)': 4 } ]
    ctx.body = {
        data:list,
        code:1,
        total:total[0]['count(*)']
    }
})

//添加的接口
router.post('/api/add',async (ctx,next) => {
    //获取前端传递的参数
    console.log(ctx.request.body)
    let {username,age,address} = ctx.request.body;
    if(username && age &&address){
        try{
            await query('insert into list (username,age,address) values (?,?,?)',[username,age,address])
            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数传递有误'
        }
    }
})

//删除
router.delete('/api/del',async (ctx,next) => {
    let {id} = ctx.query;
    if(id){
        try{
            await query('delete from list where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数传递有误'
        }
    }
})

//修改
router.put('/api/edit',async (ctx,next) => {
    let {username,age,address,id} = ctx.request.body;
    if(username && age &&address && id){
        try{
            await query('update list set username=?,age=?,address=? where id=?',[username,age,address,id])
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数传递有误'
        }
    }
})

// koa-bodyparser  接收前端post传递的参数，经过处理放到ctx.request.body

// koa-router   处理路由写接口的

//koa中间件 是一个个async await 函数 , app.use()

//ctx : 请求体  响应体  

/**
 * 
 * request:
 * 
 * ctx.url       /search?key=1
 * 
 * ctx.path      /search
 * 
 * ctx.method
 * 
 * 
 * ctx.header
 * 
 * reponse:
 * 
 * ctx.body 
 * 
*/

//next 执行下一个中间件 

// app.use(async (ctx,next) => {

// })

app.listen(3000,() => {
    console.log("服务启动成功")
})